<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Cache;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
use Venturecraft\Revisionable\RevisionableTrait;

class Advertisement extends Model
{
    // For admin log
    use RevisionableTrait;
    protected $keepRevisionOf = [
        'deleted_at'
    ];
    use SoftDeletes;

    public static function boot() {
        parent::boot();

        static::saving(function($article) {
            Cache::forget('phphub_banner');
        });
    }

    public function setImageUrlAttribute($file_name)
    {
        if (starts_with($file_name, 'http')) {
            $parser_url = explode('/', $file_name);
            $file_name = end($parser_url);
        }

        $this->attributes['image_url'] = '/uploads/advertisement/'.$file_name;
    }

    public function getImageUrlAttribute($file_name)
    {
        if (starts_with($file_name, 'http')) {
            return $file_name;
        }

        return cdn($file_name);
    }

    public static function getAllData()
    {
        $res = [];
        $now = Carbon::now()->toDateTimeString();
        $data = Advertisement::where('start_date', '<=', $now)
            ->where('end_date', '>=', $now)
            ->where('status', '=', 'yes')
            ->orderBy('sort', 'ASC')
            ->get();

        foreach ($data as $ads) {
            $res[$ads->position][] = $ads;
        }

        return $res;
    }
}
